/**
 * Copyright (C) 2012  The CFuture Android SDK Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lurencun.android.toolkit.res;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.lurencun.android.toolkit.HasContext;

import android.content.Context;
import android.util.Log;


/**
 * 
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-2-14
 */
public abstract class ResJSONHandler<T> extends HasContext{

	public ResJSONHandler(Context context) {
		super(context);
	}
	
	/**
	 * 读取string-array中的JSON数据，并解析成对象。
	 * @param resId string-array资源ID
	 * @return 解析的对象List。
	 */
	public List<T> load(int resId){
		String[] data = mContext.getResources().getStringArray(resId); 
		List<T> result = new ArrayList<T>();
		for(int i=0;i<data.length;i++){
			JSONTokener jsonParser = new JSONTokener(data[i]);
			try {
				JSONObject json = (JSONObject) jsonParser.nextValue();
				result.add(convert(json));
			} catch (Exception e) {
				Log.e("ResLoader"," ===> 解释JSON发生异常："+e.getMessage());
			}
		}
		return result;
	}
	
	/**
	 * 把JSON解析成对象
	 * @param json
	 * @return
	 */
	protected abstract T convert(JSONObject json)  throws JSONException ;

}
